/*
 * @Description: 备用的token存取方式
 * 为了让宏森嵌入联调使用，规避新版chrome的cookie跨域读取的严格限制而导致登录验证不通过的问题
 * @Author: xiangrun
 * @Date: 2020-10-13 14:44:15
 */
import Cookies from 'js-cookie'

const TokenKey = 'access_token'

export function getToken() {
  return getCookies(TokenKey)
}

export function setToken(token, setting) {
  return setCookies(TokenKey, token, setting)
}

export function removeToken() {
  return removeCookies(TokenKey)
}

// 获取cookies
export function getCookies(key) {
  try {
    const res = JSON.parse(localStorage.getItem(key))
    const { expires, data } = res || {}
    if (new Date(expires) >= new Date()) {
      return data
    } else {
      return localStorage.removeItem(key)
    }
  } catch (e) {
    console.log('获取缓存失败失败')
    console.log(e)
  }
}

// 设置cookies
export function setCookies(key, value, setting) {
  try {
    const content = JSON.stringify({ data: value, ...setting })
    // console.log(content)
    return localStorage.setItem(key, content)
  } catch (e) {
    console.log('写入缓存失败失败')
    console.log(e)
  }
  return Cookies.set(key, value, setting)
}

// 删除cookies
export function removeCookies(key) {
  return localStorage.removeItem(key)
}

